// miniprogram/pages/chatroom/chatroom.js
const db = wx.cloud.database()
const app = getApp()

const _ = db.command
Page({

    /**
     * 页面的初始数据
     */
    data: {
        roomId: '',   //房间id
        inputValue: '',  //输入值
        scr: '',    //滚动标记
        name: '',    //聊天人的名字
        chatData: [],   //聊天内容
        openId: '',     //卖家id
        avatarUrl: '',   //聊天人头像
        myId: '',    //本人id
        // goods: ''    //交易信息
    },
    onChange(event) {
        // event.detail 为当前输入的值
        this.setData({
            inputValue: event.detail
        })
    },
    addData() {
        // console.log(this.data.inputValue);
        if (!this.data.inputValue.match(/^[ ]*$/)) {//不为空

            this.data.chatData.push({
                post: "me",
                type: "text",
                time: new Date(),
                context: this.data.inputValue
            })
            let newxx = this.data.chatData[this.data.chatData.length - 1]
            try {
                if (this.data.chatData.length == 1) {  //创建新的chatroom
                    wx.cloud.callFunction({
                        // 云函数名称
                        name: 'chatroom',
                        // 传给云函数的参数
                        data: {
                            type: "newAdd",
                            newData: newxx,
                            holdUrl: this.data.avatarUrl,
                            holdName: this.data.name,
                            id: this.data.openId,     //卖家id
                            wantName: app.globalData.userInfo.nickName,
                            wantUrl: app.globalData.userInfo.avatarUrl
                        },
                    }).then(res => {
                        this.data.roomId = res.result.chatroomId
                        this.data.myId = res.result.myId
                        this.watch()
                    })
                } else {   //已经有chatroom
                    wx.cloud.callFunction({
                        // 云函数名称
                        name: 'chatroom',
                        // 传给云函数的参数
                        data: {
                            type: "add",
                            newData: newxx,  //新消息
                            roomId: this.data.roomId    //房间id
                        },
                    })
                }
                this.setData({
                    inputValue: "",
                    chatData: this.data.chatData,
                })
            } catch (e) {
                console.error(e)
            }
        }
    },
    watch() {
        const that = this
        const watcher = db.collection('chatroom').where({
            _id: this.data.roomId
        }).watch({
            onChange: function (snapshot) {
                // console.log(snapshot);

                let list = snapshot.docChanges[0].doc.list
                list.forEach(element => {
                    if (element.post == that.data.myId) {
                        element.post = "me"
                    } else {
                        element.post = "you"
                    }
                });

                that.setData({
                    chatData: list,
                })

                wx.nextTick(() => {
                    that.setData({
                        scr: `item${that.data.chatData.length - 1}`,
                    })
                })
            },

            onError: function (err) {
                console.error('the watch closed because of error', err)
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.showLoading({
            mask: true,
            title: '加载中',
        })
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('details_chatroom', (data) => {
            this.setData({
                name: data.merchant,
                openId: data._openid,
                avatarUrl: data.avatarUrl
            })
        })

        eventChannel.on('messageList_chatroom', (data) => {
            this.setData({
                openId: data.id,
                name: data.name
            })
        })
        setTimeout(() => {
            wx.cloud.callFunction({
                // 云函数名称
                name: 'chatroom',
                // 传给云函数的参数
                data: {
                    type: "in",
                    id: this.data.openId
                },
            }).then(res => {
                if (res != "404" && res.result.chatroomId) {
                    this.data.myId = res.result.myId
                    this.data.roomId = res.result.chatroomId
                    this.watch()
                }
                wx.hideLoading()
            }).catch(err => {
                console.error(err);
            })
        }, 500)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})